<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use common\collection\Common;
use common\collection\BackendCommon;
use common\helpers\PublicFun;
use backend\config\routeParams;


use PHPExcel;
use PHPExcel_Reader_Excel2007;
use PHPExcel_Reader_Excel5;
use PHPExcel_Cell_DataType;
use PHPExcel_Shared_Date;



/**
 * Site controller
 */
class CustomerController extends Controller
{

    /**
     * @inheritdoc
     */

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }
    public  function beforeAction($action){
        if(BackendCommon::init()){
            if(BackendCommon::rbac()){
                return true;
            }else{
                Yii::$app->response->redirect( ['site/error']);
            }
        }else{
            Yii::$app->response->redirect( ['login/index']);
        }
    }

    //首页
    public function actionIndex()
    {
       $lastresult['code'] = '';
       if (!empty( $_FILES ['file_stu'] ['name']))
       {
          $tmp_file = $_FILES ['file_stu'] ['tmp_name'];
          $file_types = explode ( ".", $_FILES ['file_stu'] ['name'] );
          $file_type = $file_types [count ( $file_types ) - 1];
           /*判别是不是.xls文件，判别是不是excel文件*/
           if (strtolower ( $file_type ) != "xls" && strtolower ( $file_type ) != "xlsx")              
           {
                $lastresult['code'] = 300;
                // $this->error ( '不是Excel文件，重新上传' );
           }else{
                /*设置上传路径*/
                 // $savePath = SITE_PATH . '/public/upfile/Excel/';
                 $savePath = Yii::getAlias("@webroot") . '/upload/Excel/';
                /*以时间来命名上传的文件*/
                 $str = date ( 'Ymdhis' ); 
                 $file_name = $str . "." . $file_type;
                 /*是否上传成功*/
                 if(!copy( $tmp_file, $savePath . $file_name)) 
                  {
                      // $this->error ( '上传失败' );
                    $lastresult['code'] = 100;
                  }else{
                    // $filePath = Yii::getAlias("@webroot")."/demo.xls";
                    $filePath = $savePath . $file_name;
                    $PHPExcel = new PHPExcel();
                    $PHPReader = new PHPExcel_Reader_Excel2007();
                    if (!$PHPReader->canRead($filePath)) { // 这里是用Reader尝试去读文件，07不行用05，05不行就报错。注意，这里的return是Yii框架的方式。
                        $PHPReader = new PHPExcel_Reader_Excel5();
                      if (!$PHPReader->canRead($filePath)) {
                        $errorMessage = "Can not read file.";
                        return $this->render('error', ['errorMessage' => $errorMessage]);
                      }
                    }
                    $PHPExcel = $PHPReader->load($filePath); // Reader读出来后，加载给Excel实例
                    $allSheet = $PHPExcel->getSheetCount(); // sheet数
                    $currentSheet = $PHPExcel->getSheet(0); // 拿到第一个sheet（工作簿？）
                    $allColumn = $currentSheet->getHighestColumn(); // 最高的列，比如AU. 列从A开始
                    $allRow = $currentSheet->getHighestRow(); // 最大的行，比如12980. 行从0开始
                    header("Content-type: text/html; charset=utf-8");
                    $currentSheet->getStyle('A2:A6')->getNumberFormat()->setFormatCode('yyyy-mm-dd'); // 转为A2到A6的时间格式
                    $result = $currentSheet->toArray('', true, true); // 把当前sheet转为二维数组
                    foreach ($result as $key => $value) {
                      if($key > 0 && $value[1]){
                        $ret[] = ['UserName' => $value[0],'Phone' => strval($value[1])];
                      }
                    }
                     $cookies = Yii::$app->request->cookies;
                     $admin = $cookies->get('MytipIdBack')->value;
                     $data['MytipId'] = $admin;
                     $data['ImportData'] = $ret;
                     $url = routeParams::HttpUrl('CustomerImport');
                     $lastresult = PublicFun::PostPackage($data, $url);
                     $lastresult = json_decode($lastresult['Body'],true);
                     // print_r($lastresult);exit;
                     if($lastresult['IsBizSuccess']){
                        $lastresult['code'] = 200;
                     }else{
                        $lastresult['code'] = 100;
                     }
                  }
           }

        }
       $url = routeParams::HttpUrl('CustomSourceGet');
       $opt = PublicFun::PostPackage('', $url);
       $opt = json_decode($opt['Body'],true);
       // var_dump($result);exit;
       $ret = array(
          'opt' => $opt['ItemList'],
          'excel' => $lastresult,
        );
       return $this->render('index',array('ret' => $ret));
    }
    // 分组管理
    public function actionGroupmanaget()
    {
       return $this->render('groupmanaget');
    }
    // 分组列表
    public function actionCustomerList()
    {
       $datapost = Yii::$app->request->post();
       $datapost = Common::ArrayFilter($datapost);
       $cookies = Yii::$app->request->cookies;
       $admin = $cookies->get('MytipIdBack')->value;
       $data = $datapost;
       $data['MytipId'] = $admin;
       $url = routeParams::HttpUrl('SearchCustomer');
       $result = PublicFun::PostPackage($data, $url);
       $result = json_decode($result['Body'],true);
       $ret = [
        'PageNo' => $datapost['PageNo'], 
        'PageSize' => $datapost["PageSize"],
        'total' => $result["TotalCount"],
        'data' => $result['Models']
       ];
       die(json_encode($ret));
    }
    // 获取标签
    public function actionSignList()
    {
       $datapost = Yii::$app->request->post();
       $datapost = Common::ArrayFilter($datapost);
       $cookies = Yii::$app->request->cookies;
       $admin = $cookies->get('MytipIdBack')->value;
       $data = $datapost;
       $data['MytipId'] = $admin;
       $url = routeParams::HttpUrl('MytipTagGetList');
       $result = PublicFun::PostPackage($data, $url);
       $result = json_decode($result['Body'],true);
        // print_r($result);exit;
       die(json_encode($result));
    }
    // 获取标签
    public function actionSignAdd()
    {
       $datapost = Yii::$app->request->post();
       $datapost = Common::ArrayFilter($datapost);
       $cookies = Yii::$app->request->cookies;
       $admin = $cookies->get('MytipIdBack')->value;
       $datapost['MytipId'] = $admin;
       $url = routeParams::HttpUrl('AddCustomTag');
       $result = PublicFun::PostPackage($datapost, $url);
       $result = json_decode($result['Body'],true);
        // print_r($result);exit;
       die(json_encode($result));
    }
    // 获取客户详情
    public function actionCustomerInfodetial()
    {
       $datapost = Yii::$app->request->post();
       $datapost = Common::ArrayFilter($datapost);
       $cookies = Yii::$app->request->cookies;
       $admin = $cookies->get('MytipIdBack')->value;
       $datapost['MytipId'] = $admin;
       $url = routeParams::HttpUrl('CustomerDetail');
       $result = PublicFun::PostPackage($datapost, $url);
       $result = json_decode($result['Body'],true);
       die(json_encode($result['Model']));
    }
    // 获取分组列表
    public function actionGroupList()
    {
       $cookies = Yii::$app->request->cookies;
       $admin = $cookies->get('MytipIdBack')->value;
       $data['MytipId'] = $admin;
       $url = routeParams::HttpUrl('GroupGetList');
       $result = PublicFun::PostPackage($data, $url);
       $result = json_decode($result['Body'],true);
       die(json_encode($result));
    }
    // 编辑用户信息
    public function actionCustomerEditinfo()
    {
       $datapost = Yii::$app->request->post();
       $datapost = Common::ArrayFilter($datapost);
       $cookies = Yii::$app->request->cookies;
       $admin = $cookies->get('MytipIdBack')->value;
       $datapost['MytipId'] = $admin;
       if ($datapost['type'] == 100) {
          $route = 'CustomerUpdate';
       }else{
          $route = 'CustomerCreate';
       }
       $url = routeParams::HttpUrl($route);
       $result = PublicFun::PostPackage($datapost, $url);
       $result = json_decode($result['Body'],true);
       die(json_encode($result));
    }
    // 删除用户信息
    public function actionCustomerDelinfo()
    {
       $datapost = Yii::$app->request->post();
       $datapost = Common::ArrayFilter($datapost);
       $cookies = Yii::$app->request->cookies;
       $admin = $cookies->get('MytipIdBack')->value;
       $datapost['MytipId'] = $admin;
       if($datapost['type'] == 100){
          $route = 'GroupDelete';
       }else{
          $route = 'CustomerDelete';
       }
       $url = routeParams::HttpUrl($route);
       $result = PublicFun::PostPackage($datapost, $url);
       $result = json_decode($result['Body'],true);
       die(json_encode($result));
    }
    // 上传头像 EditHead
    public function actionEditHead()
    {
        $file = $_FILES['file'];
        if ($file['error'] == 0) {
            switch ($file['type']) {
                case 'image/png' :
                    $fileext = "png";
                    break;
                case 'image/x-png' :
                    $fileext = "png";
                    break;
                case 'image/jpeg' :
                    $fileext = "jpg";
                    break;
                case 'image/gif' :
                    $fileext = "gif";
                    break;
            }

            $rand = rand(1, 100);
            $getName = uniqid() . '_' . date('Y') . date('m') . '_' . date('His') . $rand;

            $newFileName = $getName . '.' . $fileext;
            $thumbDir = Yii::getAlias("@webroot") . '/upload/head/';
            $savePath = $thumbDir . '/' . $newFileName;
            Common::createDir($thumbDir);
            if (!move_uploaded_file($file["tmp_name"], $savePath)) {
                 $info = array(
                  'IsBizSuccess' => false,
                  'ErrMsg' => '图片上传失败！'
                );
                die(json_encode($info));
            }
            $thumbPath = $thumbDir;
        } else {
            $info = array(
              'IsBizSuccess' => false,
              'ErrMsg' => '图片上传失败！'
            );
            die(json_encode($info));
        }
        $file = file_get_contents($thumbPath . $newFileName);
        $datalist = base64_encode($file);
        switch ($fileext) {
          case 'png':
            $EnumImgSuffix = 1;
            break;
          case 'jpg':
            $EnumImgSuffix = 0;
            break;
          case 'gif':
            $EnumImgSuffix = 4;
            break;
        }
        $Data = array(
            "Files" => $datalist,
            "EnumImgSuffix" => $EnumImgSuffix,
            "EnumPathName" => 9,
        );
        $url = routeParams::HttpUrl('ImageUpload');
        $result = PublicFun::PostPackage($Data, $url);
        $result = json_decode($result['Body'],true);
        if (!$result['IsBizSuccess']) {
            $info = array(
              'IsBizSuccess' => false,
              'ErrMsg' => '图片上传失败！'
            );
            die(json_encode($info));
        }
        $Photo =routeParams::HttpUrl('IMGURL') . "/" . $result['FileName'];
        $result['Photo'] =  $Photo;
        die(json_encode($result));
    }
    // 创建分组列表
    public function actionAddGroupCate()
    {
        $datapost = Yii::$app->request->post();
        $datapost = Common::ArrayFilter($datapost);
        $cookies = Yii::$app->request->cookies;
        $admin = $cookies->get('MytipIdBack')->value;
        $datapost['MytipId'] = $admin;
        $url = routeParams::HttpUrl('GroupCreate');
        $result = PublicFun::PostPackage($datapost, $url);
        $result = json_decode($result['Body'],true);
        die(json_encode($result));
    }
    // 重命名分组
    public function actionRenameGroupCate()
    {
         $datapost = Yii::$app->request->post();
         $datapost = Common::ArrayFilter($datapost);
         $cookies = Yii::$app->request->cookies;
         $admin = $cookies->get('MytipIdBack')->value;
         $datapost['MytipId'] = $admin;
         $url = routeParams::HttpUrl('GroupUpdate');
         $result = PublicFun::PostPackage($datapost, $url);
         $result = json_decode($result['Body'],true);
         die(json_encode($result));
    }
    // 移动分组
    public function actionMoveGroupElp()
    {
         $datapost = Yii::$app->request->post();
         $datapost = Common::ArrayFilter($datapost);
         $cookies = Yii::$app->request->cookies;
         $admin = $cookies->get('MytipIdBack')->value;
         $datapost['MytipId'] = $admin;
         if($datapost['type'] == 100){
            $route = 'CustomerToGroup';
         }else if($datapost['type'] == 200){
            $route = 'RemoveFromGroup';
         }
         // print_r($datapost);exit;
         $url = routeParams::HttpUrl($route);
         $result = PublicFun::PostPackage($datapost, $url);
         $result = json_decode($result['Body'],true);
         die(json_encode($result));
    }


    
    
    

}
